import React, { useEffect, useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { Button, Dropdown, Menu, message, Space, TreeSelect, Upload } from 'antd'
import ProTable from '@ant-design/pro-table'
import {
  changeStatusQuestion,
  deleteQuestion,
  excelModelQuestion,
  excelQuestion,
  getExamCategory,
  getExamQuestions,
  importQuestion
} from '@/services/examquestion'
import ProTableConfig from '@/pages/Exam/Question/ProTableConfig'
import GetTime from '@/components/GetTime'
import Create from '@/pages/Exam/Question/components/Create'
import Modal from 'antd/es/modal/Modal'
import {
  DeleteOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  VerticalAlignBottomOutlined,
  VerticalAlignTopOutlined
} from '@ant-design/icons'
import Detail from '@/pages/Exam/Question/components/Detail'

const Index = () => {
  /** 添加模态框 **/
  const [isModalShow, setIsModalShow] = useState(false)
  /** loading **/
  const [loading, setLoading] = useState(false)
  /** 题目类型 **/
  const [typeQuestion, setTypeQuestion] = useState(undefined)
  /** 试题的分类 **/
  const [category, setCategory] = useState({})
  /** 单条题目详情 **/
  const [questionDetails, setQuestionDetails] = useState({})
  /** 题目 ids **/
  const [selectedRowKeys, setSelectedRowKeys] = useState(undefined)
  /** query请求参数 **/
  const [queryParams, setQueryParams] = useState(undefined)
  const [showUploadList, setShowUploadList] = useState(true)
  /** 详情模态框 **/
  const [detailModelShow, setDetailModelShow] = useState(false)
  /** 添加子母题数据 **/
  const [subsystemId, setSubsystemId] = useState(undefined)
  const actionRef = useRef()
  const DetailActionRef = useRef()

  useEffect(async () => {
    /** 获取题库分类 **/
    let result = await getExamCategory()

    const treeData = (result || []).map(item => {
      return {
        key: item.id,
        value: item.id,
        title: item.name,
        children: item.children === undefined ? '' : (item.children || []).map((item) => {
          return {
            key: item.id,
            value: item.id,
            title: item.name,
          }
        })
      }
    })

    setCategory(treeData)
  }, [])

  /**
   * 试题的类型
   */
  const type = {
    fill: '填空题',
    checkbox: '多选题',
    radio: '单选题',
    judge: '判断题',
    short: '简答题',
    subsystem: '子母题'
  }

  /**
   * 表单请求
   *
   * @param params
   * @returns {Promise<{total, data, message: string}>}
   */
  const tableRequest = async params => {
    setLoading(true)
    // 更改默认属性名 current
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
    setQueryParams(params)
    setSelectedRowKeys(undefined)
    let examQuestionsList = await getExamQuestions(params)
    setLoading(false)

    return {
      data: examQuestionsList.data,
      message: 'success',
      total: examQuestionsList.meta.pagination.total,
    }
  }

  /***
   * 添加模态框显示
   *
   * @param e
   */
  const handleMenuClick = (e) => {
    setIsModalShow(true)
    setTypeQuestion(Object.keys(type)[e.key])
    setQuestionDetails({})
  }

  /**
   * 添加题目的菜单
   *
   * @type {JSX.Element}
   */
  const menu = (
    <Menu onClick={handleMenuClick}>
      {
        Object.values(type).map(((value, index) => {
          return (
            <Menu.Item key={index} name={index} value={value}>
              {value}
            </Menu.Item>
          )
        }))
      }
    </Menu>
  )

  /**
   * 修改题目状态
   *
   * @param ids
   * @param status
   * @returns {Promise<void>}
   */
  const handleChangeStatus = async (ids, status) => {
    const response = await changeStatusQuestion({ ids, status })
    if (response === '') {
      message.success('修改成功')
    }

    !subsystemId ? await actionRef.current?.reload() : await DetailActionRef.current?.reload()
  }

  /**
   * 多选操作
   *
   * @type {{onChange: rowSelect.onChange}}
   */
  const rowSelect = {
    onChange: (key) => {
      setSelectedRowKeys(key.join(','))
    },
  }

  /**
   * 模板下载
   *
   * @returns {Promise<void>}
   */
  const downModelQuestion = async () => {
    const response = await excelModelQuestion()
    let url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.setAttribute('download', 'question.model.xlsx')
    document.body.appendChild(link)
    link.display = 'none'
    link.href = url
    link.click()
    document.body.removeChild(link)
  }

  /**
   * 批量导出
   *
   * @returns {Promise<void>}
   */
  const downQuestion = async () => {
    const response = await excelQuestion(queryParams)
    let url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.setAttribute('download', 'question.xlsx')
    document.body.appendChild(link)
    link.display = 'none'
    link.href = url
    link.click()
    document.body.removeChild(link)
  }

  /**
   * 批量导入
   *
   * @param file
   */
  const beforeUpload = async (file) => {
    const formData = new FormData()
    formData.append('file', file)
    await importQuestion(formData)
  }

  /**
   * 更改状态
   *
   * @param file
   * @param fileList
   */
  const onChanges = ({ file, fileList }) => {
    setShowUploadList(true)
    if (file.status === 'done') {
      setShowUploadList(false)
      fileList.splice(0, fileList.length)
      actionRef.current?.reload()
    }
  }

  /**
   * 定义字段
   */
  const columns = [
    {
      dataIndex: 'id',
      title: 'ID',
      hideInSearch: true,
      hideInTable: true
    },
    {
      dataIndex: 'user_id',
      title: '用户名',
      hideInSearch: true,
      render: (_, record) => {
        return (record.user.username)
      }
    },
    {
      dataIndex: 'type',
      title: '题型',
      valueType: 'select',
      valueEnum: type,
      render: (_, record) => {
        return (
          type[record.type]
        )
      }
    },
    {
      dataIndex: 'title',
      title: '题干',
      ellipsis: true,
      valueType: 'textarea'
    },
    {
      dataIndex: 'category_id',
      title: '分类',
      valueType: 'select',
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (!!category.length) {
          return (<TreeSelect treeData={category}/>)
        }
      },
      render: (_, record) => {
        return (
          record.category.name
        )
      }
    },
    {
      dataIndex: 'status',
      title: '状态',
      valueType: 'radio',
      valueEnum: {
        0: '审核中',
        1: '审核完成',
      },
    },
    {
      dataIndex: 'fraction',
      title: '分数',
      hideInSearch: true,
      width: '5%'
    },
    {
      dataIndex: 'num',
      title: '使用次数',
      hideInSearch: true,
    },
    {
      dataIndex: 'created_at',
      title: '创建时间',
      hideInSearch: true,
    },
    {
      dataIndex: 'level',
      title: '难度',
      hideInTable: true,
      valueType: 'radioButton',
      valueEnum: {
        1: '难度1',
        2: '难度2',
        3: '难度3',
        4: '难度4',
        5: '难度5',
      }
    },
    {
      title: '操作',
      hideInSearch: 'true',
      render: (_text, record) => [
        <Button
          key={'edit'}
          style={{ marginRight: 10 }}
          onClick={() => {
            setIsModalShow(true) // 模态框显示
            setTypeQuestion(_text.type) // 设置题目类型
            setQuestionDetails(_text) // 设置题目详情
          }}
          type="primary"
          size={'small'}
        >
          编辑
        </Button>,
        <Button
          key={'delete'}
          type="danger"
          style={{ marginRight: 10 }}
          size={'small'}
          onClick={() => {
            Modal.confirm({
              icon: <ExclamationCircleOutlined/>,
              title: '确定删除吗 ?',
              onOk: async () => {
                !subsystemId ? await actionRef.current?.reload() : await DetailActionRef.current?.reload()
                return deleteQuestion(_text.id).then(res => {
                  message.success('删除成功')
                })
              },
            })
          }}
        >
          删除
        </Button>,
        _text.type === 'subsystem' ?
          <Button
            key={'detail'}
            size={'small'}
            onClick={() => {
              setDetailModelShow(true)
              setSubsystemId(_text)
            }}
          >
            详情
          </Button> : ''
      ]
    },
  ]

  const toolBarRender = [
    <Space wrap={true} size={'middle'}>
      <Button onClick={() => handleChangeStatus(selectedRowKeys, 0)}>设为审核中</Button>
      <Button onClick={() => handleChangeStatus(selectedRowKeys, 1)}>设为审核通过</Button>
      <Button icon={<DeleteOutlined/>} type={'primary'} danger onClick={() => {
        deleteQuestion(selectedRowKeys).then(async res => {
          !subsystemId ? await actionRef.current?.reload() : await DetailActionRef.current?.reload()
          message.success('删除成功')
        })
      }}>批量删除</Button>
      {
        !subsystemId ? <>
          <Button type={'primary'} icon={<VerticalAlignBottomOutlined/>} onClick={() => downQuestion()}>批量导出</Button>
          <Upload
            showUploadList={showUploadList}
            accept=".xlsx"
            name="file"
            beforeUpload={beforeUpload}
            onChange={onChanges}
            progress={{
              strokeLinecap: 'butt',
              strokeColor: {
                '0%': '#108ee9',
                '100%': '#87d068',
              },
              strokeWidth: 3,
              format: percent => `${parseFloat(percent.toFixed(2))}%`,
            }}
          ><Button icon={<VerticalAlignTopOutlined/>}>批量导入</Button></Upload>
          <Button icon={<DownloadOutlined/>} type={'primary'} key="out"
                  onClick={() => downModelQuestion()}>下载Excel模板</Button>
        </> : ''
      }
      <Dropdown overlay={menu} trigger="click">
        <Button icon={<PlusOutlined/>} type={'primary'}>添加题目</Button>
      </Dropdown>
    </Space>
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <ProTable
        {...ProTableConfig}
        options={{ density:false, fullScreen:false, setting:false }}
        actionRef={actionRef}
        loading={loading}
        columns={columns}
        rowSelection={{ ...rowSelect }}
        request={(params) => tableRequest(params)}
        toolBarRender={() => toolBarRender}
      />
      <Create
        actionRef={actionRef}
        DetailActionRef={DetailActionRef}
        typeQuestion={typeQuestion}
        isModalShow={isModalShow}
        setIsModalShow={setIsModalShow}
        type={type}
        category={category}
        questionDetails={questionDetails}
        setQuestionDetails={setQuestionDetails}
        subsystemId={subsystemId}
      />
      <Detail
        DetailActionRef={DetailActionRef}
        detailModelShow={detailModelShow}
        setDetailModelShow={() => setDetailModelShow(false)}
        columns={columns}
        handleChangeStatus={handleChangeStatus}
        type={type}
        menu={menu}
        toolBarRender={toolBarRender}
        category={category}
        questionDetails={questionDetails}
        setQuestionDetails={setQuestionDetails}
        subsystemId={subsystemId}
        rowSelect={rowSelect}
      />
    </PageContainer>
  )
}
export default Index
